<?php

namespace IDock\Insurance\MACN\Response;


use IDock\Http\Response;
use SimpleXMLElement;

class AllMACNResponse extends Response
{

    public function resolve(): Response
    {
        $body = $this->getBody();
        $body = iconv('UTF-8','GBK',$body);
        if ($body) {
            libxml_disable_entity_loader();
            $body = simplexml_load_string($body);
            $body = $this->objectToArray($body);
            $errorCode = $body['head']['statusCode'] ?? '';
            if ($errorCode !== 'success' && $errorCode !== '000000') {
                $this->setError($body['head']['description'] ?? '未知错误或无错误提示');
                return  $this;
            }
            $this->setBody($body['body'] ?? '');
        }

        return $this;
    }

    protected function objectToArray($object) {
        if( count($object)==0 )  return trim((string)$object);
        $result = array();
        $object = is_object($object) ? get_object_vars($object) : $object;
        foreach ($object as $key => $val) {
            $val = (is_object($val) || is_array($val)) ? $this->objectToArray($val) : $val;
            $result[$key] = $val;
        }
        return $result;
    }

    protected function errorTrans($error)
    {

    }
}
